<?php

namespace app\controller\api;

use app\model\RailwayStation as RailwayStationModel;
use app\model\ReturnCode;

class Station extends Base
{

    public function stations()
    {
        $rid = $this->request->get('rid');
        $crid = $this->request->get('crid');
        $item_id = $this->request->get('item_id');
        
        // 获取检查记录信息
        $checkRecord = \app\model\CheckRecord::where('id', $crid)->find();
        if (!$checkRecord) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '检查记录不存在');
        }

        // 获取检查项目信息
        $checkItem = \app\model\CheckItem::where('id', $item_id)->find();
        if (!$checkItem) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '检查项目不存在');
        }

        // 获取检查类型信息
        $checkType = \app\model\CheckType::where('id', $checkItem['type_id'])->find();
        if (!$checkType) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '检查类型不存在');
        }

        $where = [
            ['railway_id', '=', $rid]
        ];
        
        // 如果有范围限制
        if ($checkRecord['range_ids']) {
            $rangeArray = explode(',', $checkRecord['range_ids']);
            $where[] = ['id', 'in', $rangeArray];
        }
        
        $stations = RailwayStationModel::where($where)
            ->order(['sort' => 'asc'])
            ->select()
            ->toArray();
        
        // 根据方向过滤站点
        if (!empty($stations)) {
            if ($checkType['direction'] == 1) { // 上行，排除头站点
                array_shift($stations);
            } else if ($checkType['direction'] == 2) { // 下行，排除尾站点
                array_pop($stations);
            }
        }
        
        return $this->buildSuccess($stations);
    }

    public function detail()
    {
        $id = $this->request->get('id');
        $where = ['id' => $id];
        $data = RailwayStationModel::where($where)
            ->find()
            ->toArray();
        return $this->buildSuccess($data);
    }
}
